#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>

sem_t sem;
sem_t sem2;

int food = 0;

void* pthread_func(void *arg){
    
    while(1){

        sleep(1);
        sem_wait(&sem); //P操作

        printf("正在生产食物...\n");
        food++;
        printf("生产食物完毕...目前的食物总数:%d\n", food);

        sem_post(&sem2); //V操作

    }

}

void* pthread_func2(void *arg){

    while(1){

        sleep(1);
        sem_wait(&sem2); //P操作

        printf("正在消耗食物...\n");
        food--;
        printf("消费食物完毕...目前的食物总数:%d\n", food);

        sem_post(&sem); //V操作

    }

}


int main(int argc, char const *argv[])
{
    pthread_t thread = -1;
    pthread_t thread2 = -1;
    int ret = -1;
    sem_init(&sem, 0, 1); //初始化信号
    sem_init(&sem2, 0, 0);

    ret = pthread_create(&thread, NULL, pthread_func, NULL); //创建线程
    if (ret != 0){
        printf("pthread_create failed\n");
        return -1;
    }

    ret = pthread_create(&thread2, NULL, pthread_func2, NULL); //创建线程
    if (ret != 0){
        printf("pthread_create failed\n");
        return -1;
    }

    //回收线程
    pthread_join(thread,NULL); 
    pthread_join(thread2,NULL);

    return 0;
}
